#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <cstring>


#define BUFFSIZE 1024

int main(int argc, char *argv[])
{
    int server_sockfd = 0;
    int len = 0;
    socklen_t sin_size = 0;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    char buf[BUFFSIZE] = {0};

    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(8000);

    if((server_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket error!\n");
        return -1;
    }

    if(bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0)
    {
        perror("bind error!\n");
        return -1;
    }
    sin_size= sizeof(struct sockaddr_in);
    while(1)
    {
        if((len = recvfrom(server_sockfd, buf, BUFFSIZE, 0, (struct sockaddr*)&client_addr, &sin_size)) < 0)
        {
            perror("recvfrom error!\n");
            return -1;
        }

        printf("recv from: %s\n",inet_ntoa(client_addr.sin_addr));
        buf[len] = '\0';
        printf("recv is: %s\n",buf);
        if(len <= 0)
        {
            break;
        }
    }
    close(server_sockfd);

    return 0;
}
